<div id="TB_load"><?php echo $this->Html->image("loading_animation.gif")?></div>
<?php echo $this->Session->flash(); ?>
<div id="register_holder">
	<div id="register_search">
		<form action="<?php echo $webroot?>Point_of_sale/salesadd" method="post" accept-charset="utf-8" id="add_item_form">					
		<input type="text" name="item" value="" id="item" size="40" accesskey="i" class="ui-autocomplete-input search_bg" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
		</form>
	</div>
	<div class="hide"><?php $form_id="line_item_form_0";?>
			<form action="<?php echo $webroot?>Point_of_sale/edit_item/1" method="post" accept-charset="utf-8" class="line_item_form" id="<?php echo $form_id?>">
				<input type="hidden" value="0" name="id">		
				<input type="hidden" value="0" name="price">		
				<input type="hidden" value="0" name="discount_type">		
				<input type="hidden" value="0" name="discount">		
				<input type="hidden" value="0" name="layby_amount">		
			</form>
	</div>
			<table id="register">
				<thead>
					<tr>
						<th id="reg_item_del"><input type="checkbox" class="check_all" value="0" name="sale_item_check"/></th>
						<th id="reg_item_name">Item Name</th>
						<th id="reg_item_number">Brand</th>
						<th id="reg_item_stock">Color</th>
						<th id="reg_item_price">Price</th>
						<th id="reg_item_discount" colspan="2">Discount</th>
						<th id="reg_item_total">Total</th>
						<th id="reg_item_layby">Layby/Amount</th>
					</tr>
				</thead>
				<tbody id="cart_contents">
				<?php if(empty($sale["cart_count"])){?>
					<tr>
						<td colspan="9">
							<div class="warning_message" style="padding:7px;">There are no items in the cart</div>
						</td>
					</tr>
					<?php }else{?>
					<?php foreach($sale["items"] as $k=>$v){?>
					<?php 
						$form_same_class="line_item_class_".$k;
						$islayby=!empty($v["Item"]["layby_amount"]);
					?>
					<tr class="<?php echo empty($v["Item"]["status"])?"":"disabled"?>">
									<td id="reg_item_del"><input type="checkbox" class="check_one" value="<?php echo $k?>" name="sale_item_check"/></td>
									<td id="reg_item_name"><?php echo $v["Item"]["name"]?></td>
									<td id="reg_item_number"><?php echo $v["Brand"]["name"]?></td>
									<td id="reg_item_stock"><?php echo $v["Color"]["name"]?></td>
									<td id="reg_item_price" style="width: 102px;"><input type="text" readonly="readonly" name="price" value="<?php echo $v["Item"]["original_price"]?>" size="6"></td>
									<td id="reg_item_qty">
									<select name="discount_type" class="<?php echo $form_same_class?>">
										<option value="0" <?php echo empty($v["Item"]["discount_type"])?"selected":""?>>Disc %</option>
										<option value="1" <?php echo empty($v["Item"]["discount_type"])?"":"selected"?>>Amount $</option>
									</select></td>
									<td id="reg_item_discount" style="width: 68px;"><input type="text" name="discount" value="<?php echo $v["Item"]["discount"]?>" size="6"  data-id="<?php echo $k?>" data-tclass="<?php echo $form_same_class;?>" data-price="<?php echo $v["Item"]["original_price"]?>" class="input_discount discount_<?php echo $form_same_class;?>"></td>
									<td id="reg_item_total">$<?php echo $v["Item"]["total"]?></td>
									<td id="reg_item_layby"><input type="checkbox" class="layby" data-id="<?php echo $k?>" <?php echo $islayby?"checked":""?>/><input type="text" value="<?php echo $islayby?$v["Item"]["layby_amount"]:0?>" size="6" class="layby_input layby_<?php echo $form_same_class?>" data-tclass="<?php echo $form_same_class;?>" data-id="<?php echo $k?>"
									data-price="<?php echo $v["Item"]["original_price"]?>" <?php echo $islayby?"":"disabled"?>/></td>
					</tr>
						
	
					<?php } }?>
					<?php if(empty($sale["id"])){?>
					<tr class="tr_tool">
						<td colspan="9">
							<div class="tools">
								<input class="btn" id="delete_items" value="Delete" type="button">
							</div>
						</td>
					</tr>
					<?php }?>
				</tbody>
				</table>
</div>
<div id="overall_sale">
	<div id="regist_payment">
		<?php $form_id="select_customer_form";?>
		<form action="<?php echo $webroot?>Point_of_sale/edit_item/3" method="post" accept-charset="utf-8"  id="<?php echo $form_id?>">	
		<?php if(empty($sale ["customer"])){?>
		<div class="search_p" id="customer_info_empty">
			<p>Select Customer (Optional)</p>
			<p>&nbsp;<input type="text" name="customer" value="Type customer name..." id="customer" size="30" accesskey="c" class="ui-autocomplete-input search_bg" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true"></p>
			<p>OR &nbsp;<a class="btn customer-popup-window">New Customer</a></p>
			<div class="clearfix"></div>
		</div>
		<?php }else{?>
		<div id="customer_info_filled">
		    <h5 style="text-decoration:underline;">Customer</h5>
			<div id="customer_name"><?php echo $sale ["customer"]["name"]?></div>
			<div id="customer_email"><?php echo $sale ["customer"]["email"]?></div>
			<div id="customer_remove"><a href="javascript:void(0);" id="delete_customer" class="btn">Incorrect customer?</a></div>
			<div class="clearfix"></div>
		</div>
		<?php }?>
		</form>
	</div>
	<div id="sale_details">
	<?php $form_id="sale_details_form";?>
	<form action="<?php echo $webroot?>Point_of_sale/edit_item/2" method="post" accept-charset="utf-8" class="line_item_form" id="<?php echo $form_id?>">
		<table id="sales_items">
			<tbody>
			<tr>
				<td class="left">Items In Cart:</td>
				<td class="right"><?php echo $sale["cart_count"]?></td>
			</tr>
			<tr>
				<td class="left">Sub Total:</td>
				<td class="right">$<?php echo $sale["sub_total"]?></td>
			</tr>
			</tbody>
		</table>
		<?php if($sale["cart_count"]>0){?>
		<table id="sales_discount">
			<tr>
				<td colspan="2" class="title">Discount</td>
			</tr>
			<tr>
				<td class="left">
					<select name="discount_type" <?php if($sale["laybyed"]){echo "disabled";}?>>
						<option value="0" <?php echo empty($sale["discount_type"])?"selected":""?>>Disc %</option>
						<option value="1" <?php echo empty($sale["discount_type"])?"":"selected"?>>Amount $</option>
					</select>
				</td>
				<td class="right">
					<input type="text" <?php if($sale["laybyed"]){echo "disabled";}?> name="discount" value="<?php echo $sale["discount"]?>" size="6"  data-fid="<?php echo $form_id?>" class="total_input_discount">
				</td>
			</tr>
		</table>
		<?php }?>
		<table id="sales_items_total">
			<tbody>
				<tr>
					<td class="left">Total:</td>
					<td class="right">$<?php echo $sale["total"]?></td>
				</tr>
			</tbody>
		</table>
	</form>
	</div>
	<?php if($sale["cart_count"]>0){?>
	<div id="Payment_Types">
		<table id="amount_due">
			<tbody>
				<tr class="">
				<td>
					<div class="float_left" style="font-size:.8em;">Amount Due:</div>
				</td>
				<td style="text-align:right; ">
					<div class="float_left" style="text-align:right;font-weight:bold;">$<?php echo $sale ["balance"];?></div>
					<input type="hidden" value="<?php echo $sale ["balance"];?>" id="amount_dues">
				</td>
				</tr>
			</tbody>
		</table>
			<div id="make_payment">
				<?php $form_id="add_payment_form"; if(isset($sale ["customer"]["id"])){ $cId = $sale ["customer"]["id"];} else {$cId = "";} ?>
				<form action="<?php echo $webroot?>Point_of_sale/edit_item/4" method="post" accept-charset="utf-8"  id="<?php echo $form_id?>">							
				
			<input type="hidden" value="<?php echo $cId;?>" name="cId" id="cId" />			
			<input type="hidden" value="<?php echo Configure::read('constantVar.siteurl');?>" name="SiteURL" id="SiteURL" />
				<?php if(!empty($sale["id"])){?>
				<input type="hidden" name="id" value="<?php echo $sale["id"]?>">
				<?php }?>
				<table id="make_payment_table">
					<tbody><tr id="mpt_top">
						<td id="add_payment_text">
							Add Payment:
						</td>
						<td>
							<select name="payment_type" id="payment_types">
							<?php foreach ($payment_types as $pay_t){?>
							<option value="<?php echo $pay_t["PaymentType"]["id"]?>" <?php echo !empty($sale["payment_type"])&&$sale["payment_type"]==$pay_t["PaymentType"]["id"]?"selected":""?>><?php echo $pay_t["PaymentType"]["name"]?></option>
							<?php }?>
							</select>									
						</td>
					</tr>
					<tr id="mpt_bottom">
						<td id="tender" colspan="2">
							<input type="text" name="amount_tendered" required value="<?php echo $sale ["balance"];?>" id="amount_tendered" size="10" accesskey="p" data-fid="<?php echo $form_id?>">									
						</td>
					</tr>
				</tbody></table>
				<div class="btn btn-success" id="add_payment_button">
					<span>Complete Sale</span>
				</div>
				</form>
			</div>
	</div>
	<?php }?>
<form action="<?php echo $webroot?>Point_of_sale/edit_item/5" method="post" id="delete_items_form">
	<input name="id" value="" id="delete_ids">
</form>

<?php echo $this->Html->css('/css/ui-lightness/jquery', null, array('inline' => false));?>
<?php echo $this->Html->script('jquery-ui-1.9.2.custom.min.js', array('inline' => false));?>
<script type="text/javascript">
$(document).ready(function(){
	//设置是否分期
	$("input.layby").bind("click",function(){
		var hascheck=false;
		$("input.layby").each(function(index,elem){
			if($(elem).attr("checked")){
				hascheck=true;
				$(elem).next().attr("disabled",false);
			}else{
				$(elem).next().attr("disabled",true).val("0");
			}
		});
		if(!$(this).attr("checked")){
			//$(this).next().change();
		}
		$("#sales_discount :input[name='discount_type']").attr("disabled",hascheck);
		$("input.total_input_discount").attr("disabled",hascheck).val("0");
	});
	//付款总额小于需要付款的金额，则支付完成按钮变成pay
	$("input#amount_tendered").live("change",function(){
		var pay_money=$(this).val();
		var amount_due=$("#amount_dues").val();
		if((pay_money-amount_due)<0){
			$("#add_payment_button span").html("Pay");
		}else{
			$("#add_payment_button span").html("Complete Sale");
		}
		return false;
	});
	<?php if(empty($sale["id"])){?>
	$("input.input_discount").live("change",function(){
		var form_id = "line_item_form_0";
		$("#"+form_id).find("input[name='id']").val($(this).data("id"));
		var discount_class=$(this).data("tclass");
		$("#"+form_id).find("input[name='discount_type']").val($("."+discount_class).val());
		$("#"+form_id).find("input[name='discount']").val($(this).val());
		$("#"+form_id).find("input[name='price']").val($(this).data("price"));
		$("#"+form_id).find("input[name='layby_amount']").val($(".layby_"+discount_class).val());
		$("#"+form_id).submit();
		return false;
	});
	$("input.layby_input").live("change",function(){
		var form_id = "line_item_form_0";
		$("#"+form_id).find("input[name='id']").val($(this).data("id"));
		var discount_class=$(this).data("tclass");
		$("#"+form_id).find("input[name='discount_type']").val($("."+discount_class).val());
		$("#"+form_id).find("input[name='discount']").val($(".discount_"+discount_class).val());
		$("#"+form_id).find("input[name='price']").val($(this).data("price"));
		$("#"+form_id).find("input[name='layby_amount']").val($(".layby_"+discount_class).val());
		$("#"+form_id).submit();
		return false;
	});
	$("input.total_input_discount").live("change",function(){
		var form_id = $(this).data("fid");
		$("#"+form_id).submit();
		return false;
	});
	$( "#item" ).autocomplete({
		source: '<?php echo $webroot?>items/search.json',
		delay: 10,
		autoFocus: false,
		minLength: 0,
		select: function(event, ui)
		{
			event.preventDefault();
			$( "#item" ).val(ui.item.value);
			$('#add_item_form').ajaxSubmit({target: "#register_container", beforeSubmit: salesBeforeSubmit, success: salesSuccess});
		},
		change: function(event, ui)
		{
			if ($(this).attr('value') != '' && $(this).attr('value') != "Type item name or scan barcode...")
			{
				$("#add_item_form").ajaxSubmit({target: "#register_container", beforeSubmit: salesBeforeSubmit, success: salesSuccess});
			}
	
			$(this).attr('value',"Type item name or scan barcode...");
		}
	});
	$( "#customer" ).autocomplete({
		source: '<?php echo $webroot?>customers/search_name.json',
		delay: 10,
		autoFocus: false,
		minLength: 0,
		position: { my : "right top", at: "right bottom" },
		select: function(event, ui)
		{
			$("#customer").val(ui.item.value);
			$('#select_customer_form').ajaxSubmit({target: "#register_container", beforeSubmit: salesBeforeSubmit, success: salesSuccess});
		}
	});
	$('#item,#customer').click(function(){$(this).attr('value','');});
	$('#customer').blur(function(){$(this).attr('value',"Type customer name...");});
	//删除客户
	$("#delete_customer").click(function(){
		$('#customer').val("");
		$('#select_customer_form').ajaxSubmit({target: "#register_container", beforeSubmit: salesBeforeSubmit, success: salesSuccess});
	});
	//全选
	$(".check_all").bind("click",function(){
		var name=$(this).attr("name");
		if($(this).attr("checked")){
			$(".check_one[name='"+name+"']").attr("checked",true);
			}else{$(".check_one[name='"+name+"']").attr("checked",false);}
	});
	//单个选择
	$(".check_one").bind("click",function(){
			var name=$(this).attr("name");
			var flag=true;
			$(".check_one[name='"+name+"']").each(function(){
					if(!$(this).attr("checked")){flag=false;}
				});
			$(".check_all[name='"+name+"']").attr("checked",flag);
	});
	//批量移除购物车
	$("#delete_items").click(function(){
		if($(".check_one[name='sale_item_check']").length>0){
			var id="0";
			$(".check_one[name='sale_item_check']").each(function(){
				if($(this).attr("checked")){
					id+=";"+$(this).val();
				}
			});
			$("#delete_ids").val(id);
			$('#delete_items_form').ajaxSubmit({target: "#register_container", beforeSubmit: salesBeforeSubmit, success: salesSuccess});
		}else{
			alert("No item selected!!");
		}
	});
	<?php }?>
	//支付按钮
	$("#add_payment_button").click(function(){
	    var pay_money=$("#amount_tendered").val();
	    var amount_due=$("#amount-dues").val();
	    if((pay_money-amount_due)<0){
	    //haven't finish paying?? continue..
	        $('#add_payment_form').ajaxSubmit({target:"#regiter_consider", beforeSubmit: salesBeforeSubmit, success: salesSuccess});
	    }else{
	    //payment done, jump to receipt
	        $('#add_payment_form').ajaxSubmit({beforeSubmit: salesBeforeSubmit, success:paySuccess});
	        //$("#receipt_dialog").dialog("open");
	    }

	    //}
		//$('#add_payment_form').ajaxSubmit({target: "#wrapper", beforeSubmit: salesBeforeSubmit, success: salesSuccess});

	});
	//自动关闭消息框
	setTimeout(function(){$("#flashMessage").hide();},5000);
	
});
function salesBeforeSubmit(formData, jqForm, options)
{
	$("#add_payment_button").hide();
	$("#finish_sale_button").hide();
	$("#TB_load").show();
}

//open a dialog,when closed, refresh
function paySuccess(responseText, statusText, xhr, $form){
	$("#recipt_dialog").dialog("open");

	window.location.href = responseText;
	 
	   //$("#recipt_dialog #dialog_content").html('<iframe src="SetPaperCenterDialog6.htm?bankid=2&amp;quesid=1746530" scrolling="no" frameborder="0" width="100%" height="330"></iframe>');
	   var receipt_html=$(responseText).find("#receipt_wrapper");
	   $("#recipt_dialog #dialog_content").html(receipt_html);
}


function salesSuccess(responseText, statusText, xhr, $form)
{
}
$(document).ready(function() {
	$("#recipt_dialog").dialog({
		autoOpen: false,
		resizable:false,
		dialogClass:"item-refund-dialog",
		width:1024,
		modal:true,
		position: { my: "center top", at: "center top" } ,
		beforeClose: function( event, ui ) {
				//刷新当前页
			window.location.reload();
			},
		buttons:{
			"Print":function(){
					　　printwindow=window.open("", "newwin", "height=800, width=1024,toolbar=no,menubar=no");
					　　//写成一行
					　　printwindow.document.write("<html>")
					　　printwindow.document.write("<head>")
					　　printwindow.document.write("<title>Print Receipt</title>")
					　　printwindow.document.write('<?php echo $this->Html->css('default') ?>')
					　　printwindow.document.write('<?php echo $this->Html->css('bootstrap.min')?>')
					　　printwindow.document.write("</head>")
					　　printwindow.document.write("<body bgcolor=#ffffff>")
					　　printwindow.document.write( $("#recipt_dialog #dialog_content").html());
					　　printwindow.document.write("</body>")
					　　printwindow.document.write("</html>")
					　　printwindow.document.close()
					  printwindow.print();
					  printwindow.window.close();
			},
			"Close":function(){
				$(this).dialog("close");
			}}
	});
});
</script>
</div>




<script type="text/javascript">

    $(document).ready(function() {

        $('.customer-popup-window').click(function(){

           var popupBoxCustomer = '#popup-box-customer';

           $(popupBoxCustomer).fadeIn(400);

           var popMargTop = ($(popupBoxCustomer).height() + 24) /2;
           var popMargLeft = ($(popupBoxCustomer).height() + 24) /2;

           $(popupBoxCustomer).css({
            'margin-top' : -popMargTop,
            'margin-left' : -popMargLeft
           });

           $('body').append('<div id="mask"></div>');
           $('#mask').fadeIn(400);
           return false;

        });
        
        
		$('button.close, #mask').bind('click', function(){
            $('#mask, .custpopupInfo').fadeOut(400, function(){
                $('#mask').remove();
            });
            return false;

        });
    });

$(document).keyup(function(e) {
    if ( e.keyCode == 27) {
        $('#mask, .custpopupInfo, #popup-box-customer').fadeOut(400);
        return false;
    }
});

//not working part
$('#mask').click(function(){
        $('#mask, .custpopupInfo,#popup-box-customer').fadeOut(400);
});
//not working part

</script>



<!-- popup button for customer begins -->
<?php echo $this->Html->script('jquery.form'); ?>
<div id="popup-box-customer" class="custpopupInfo">
    <h3>New Customer:</h3>
    <?php echo $this->Form->create('Customer',array("url"=>array("controller"=>"customers"))); ?>
	<fieldset class="posForm1">
        <legend><?php echo __('Personal details'); ?></legend>
        <input type="hidden" value="<?php echo rand(1000, 9999)?>" name="random" style="height:25px;" />
        <?php echo $this->Form->input('first_name', array('label' => 'First name', 'error' => array('attributes' => array('class' => 'myError') )  )); ?>
        <?php echo $this->Form->input('last_name', array('label' => 'Last name', 'error' => array('attributes' => array('color' => 'red') )  )); ?>
        <?php echo $this->Form->input('dob', array('label' => 'Date of birth','dateFormat' => 'DMY','minYear' => date('Y') - 100,'maxYear' => date('Y') + 1,'style'=> ('width:90px; height:30px;')));?>
        <?php echo $this->Form->input('gender_id', array('label' => 'Gender'));?>
        <?php echo $this->Form->input('phone', array('label' => 'Phone number'));?>
        <?php echo $this->Form->input('email', array('label' => 'Email address', 'style'=> ('width:300px; height:21px;')));?>
    </fieldset>

    <fieldset class="posForm2">
        <legend><?php echo __('Address'); ?></legend>

        <?php
        echo $this->Form->input('street', array(
                    'label' => 'Street',
        ));
        echo $this->Form->input('suburb', array(
                    'label' => 'Suburb'
        ));
        echo $this->Form->input('city', array(
                    'label' => 'City'
        ));
        echo $this->Form->input('state', array(
                    'label' => 'State',
        ));
        echo $this->Form->input('postcode', array(
                    'label' => 'Postal Code',
        ));
        echo $this->Form->input('country', array(
                    'label' => 'Country',
        ));
        ?>
    </fieldset>


    <fieldset class="POSForm3" >
        <legend><?php echo __('Account'); ?></legend>

        <?php
            echo $this->Form->input('username', array(
                        'label' => 'Username','error' => array('attributes' => array('color' => 'red') )
            ));

            echo $this->Form->input('password', array(
                        'label' => 'Password',
            ));

            echo $this->Form->input('confirm_password', array('label' => 'Confirm password',
            'error' => array('attributes' => array('class' => 'field_error'))
            ));

            echo $this->Form->input('group_id', array(
                        'label' => 'User group',
                        'type' => 'hidden',
            ));
        ?>
    </fieldset>

	<button type="button" class="close">Close</button><br>
	<?php echo $this->Form->end(__('Submit')); ?>
</div>

<script type="text/javascript">
$(document).ready(function(){
	 $('#CustAddForm').ajaxForm({
		 complete: function (xhr) {
			 var data = JSON.parse(xhr.responseText);
			 alert(data.message);
			 //Save successful, reload page
			 if(data.status){
				 $("#SaleCustId").empty();
				 $.each(data.customerlist,function(index,elem){
					 $("#SaleCustId").append("<option value="+elem.id+">"+elem.name+"</option>");
					 });
				}
			$('#mask, .custpopupInfo').fadeOut(400);
			$("#CustAddForm #CustomerName").val("");
		    return false;
		   }
		});

});
</script>
<!-- popup button for customer ends -->